#!/bin/sh

DAEMON_HOME=`pwd`

LOG_DIR="${DAEMON_HOME}/log"
BIN_DIR="${DAEMON_HOME}"
BIN_NAME="daemon_gis_useraddr"
ETC_DIR="${DAEMON_HOME}"
ETC_NAME="${BIN_NAME}.conf"
STOP_TIMEOUT=3
PROCESS_NUM=1

print_usage() {
  echo "usage: $0 {start|stop|restart|show|crontab}"
  exit 1
}

log() {
  echo "`date '+[%Y-%m-%d %H:%M:%S]'` $1"
}

process_num() {
  local num=`ps aux | grep ${DAEMON_HOME}/${BIN_NAME} | grep -v ${BIN_NAME}.sh | grep -v grep | grep -v tail | grep -v vi | wc -l`
  echo $num
}

start() {
  log "$BIN_NAME is starting..."

  if [ $(process_num) -ge $PROCESS_NUM ] ; then
    log "$BIN_NAME is already there."
    return
  fi 
  
  cd $BIN_DIR
  rm -f log
  ln -s /data/applog/$BIN_NAME  log
  $BIN_DIR/$BIN_NAME $ETC_DIR/$ETC_NAME & 

  log "$BIN_NAME is started..."
}

daemon_pids() {
  ps aux | grep ${DAEMON_HOME}/${BIN_NAME} | grep -v ${BIN_NAME}.sh | grep -v grep | grep -v tail | grep -v vi | awk '{print $2}'
}

stop() {
  log "$BIN_NAME is stopping..."

  if [ $(process_num) -eq 0 ] ; then
    log "$BIN_NAME is already gone."
    return
  fi

  kill -15 $(daemon_pids)

  SLEEP=$STOP_TIMEOUT
  while [ $SLEEP -ge 0 ]; do
    if [ $(process_num) -eq 0 ] ; then
      break
    fi

    if [ $SLEEP -gt 0 ] ; then
      log "waiting $SLEEP seconds for $BIN_NAME to stop..."
      sleep 1
    elif [ $SLEEP -eq 0 ] ; then
      if [ $(process_num) -gt 0 ] ; then
        log "$BIN_NAME failed to stop in $STOP_TIMEOUT seconds, force to kill."
        kill -9 $(daemon_pids)
      fi
    fi
    
    SLEEP=`expr $SLEEP - 1`
  done

  log "$BIN_NAME is stopped..."
}

restart() {
  stop
  start
}

show() {
  ps -awef | grep ${DAEMON_HOME}/${BIN_NAME} | grep -v ${BIN_NAME}.sh | grep -v grep
}

crontab() {
  echo "*/10 * * * * ${DAEMON_HOME}/auto_restart.sh >/dev/null 2>&1"
}

main() {
  case "$COMMAND" in
    start)
      start
      ;;
    stop)
      stop
      ;;
    restart)
      restart
      ;;
    show)
      show
      ;;
    crontab)
      crontab
      ;;
    *)
      print_usage 
  esac
}

[ $# -gt 0 ] || print_usage
COMMAND=$1

main